package cn.xiaoxiang.basic.controller;

import cn.xiaoxiang.basic.util.AjaxResult;
import cn.xiaoxiang.basic.util.FastdfsUtil;
import cn.xiaoxiang.basic.util.AjaxResult;
import cn.xiaoxiang.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
* @Description: fastdfs接口层
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/5/17 10:13
*/
@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {

    /**
    * @Title: upload
    * @Description: fastdfs文件上传接口
    * @Author: Mr.She
    * @Version: 1.0
    * @Date:  2022/5/17 10:37
    * @Parameters: * @param file
    * @Return cn.itsource.basic.utils.AjaxResult
    */
    @PostMapping("upload")
    public AjaxResult upload(@RequestPart(value = "file", required = true) MultipartFile file) throws IOException {
        // 1.得到文件扩展名
        String filename = file.getOriginalFilename();
        String suffix = FilenameUtils.getExtension(filename);
        // 2.上传图片，根据字节+文件扩展名，得到文件访问路径
        // /group1/M00/00/05/oYYBAGKCO-6AdKyoAAEOykzR2Hc97_350x350.jpeg
        String path = FastdfsUtil.upload(file.getBytes(), suffix);
        // 3.返回成功信息+文件访问路径
        return AjaxResult.me().success(path);

        //        try {
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return AjaxResult.me().setMsg("系统繁忙，请重试！");
//        }
    }


    /**
    * @Title: delete
    * @Description: fastdfs删除接口
    * @Author: Mr.She
    * @Version: 1.0
    * @Date:  2022/5/17 10:37
    * @Parameters: * @param file
    * @Return cn.itsource.basic.utils.AjaxResult
    */
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path", required = true) String path){
        try {
            // 因为删除需要组名+图片路径，所以我们需要把前端传递进来的图片路径进行分割
            // /group1/M00/00/05/oYYBAGKCO-6AdKyoAAEOykzR2Hc97_350x350.jpeg
            // 1.得到组名和路径名称
            // 1.1.得到组名
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            // 1.2.得到图片路径
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            // 2.调用工具类方法进行删除，传递组名和图片路径名称
            FastdfsUtil.delete(groupName, remotePath);
            // 3.返回成功信息+文件访问路径
            return AjaxResult.me().success(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("系统繁忙，请重试！");
        }
    }

}